import Mock from 'mockjs';
import article from "@/mock/article";
import users from "@/mock/users";
import { param2Obj } from '@/utils/utils'


const mockDate = [
    ...article,
    ...users
];


function mockXHR() {
    // mock patch
    // https://github.com/nuysoft/Mock/issues/300
    Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
    Mock.XHR.prototype.send = function() {
        if (this.custom.xhr) {
            this.custom.xhr.withCredentials = this.withCredentials || false

            if (this.responseType) {
                this.custom.xhr.responseType = this.responseType
            }
        }
        this.proxy_send(...arguments)
    }

    function XHR2ExpressReqWrap(respond) {
        return function(options) {
            let result = null
            if (respond instanceof Function) {
                const { body, type, url } = options
                // https://expressjs.com/en/4x/api.html#req
                result = respond({
                    method: type,
                    body: JSON.parse(body),
                    query: param2Obj(url)
                })
            } else {
                result = respond
            }
            return Mock.mock(result)
        }
    }
    // mock 函数的 url 不能直接传递， 因为get 请求拼接参数无法命中 url
    mockDate.forEach(item => {
        Mock.mock(new RegExp(item.url), item.type || 'get', XHR2ExpressReqWrap(item.response));
    });
}


export {
    mockDate,
    mockXHR
}
